﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using GalaSoft.MvvmLight.Messaging;

namespace Miris.HumanMilkAnalyser.WPF.Shared
{
    public class WindowBase : Window
    {
        public WindowBase()
        {
            RegisterMessages();

            Dispatcher.ShutdownStarted += Dispatcher_ShutdownStarted;
            Unloaded += WindowBase_Unloaded;
        }

        //protected override void OnPreviewMouseLeftButtonDown(System.Windows.Input.MouseButtonEventArgs e)
        //{
        //    base.OnPreviewMouseLeftButtonDown(e);
        //    DragMove();
        //}

        protected virtual void Dispatcher_ShutdownStarted(object sender, EventArgs e)
        {
            Cleanup();
        }

        protected virtual void WindowBase_Unloaded(object sender, RoutedEventArgs e)
        {
            Cleanup();
        }

        /// <summary>
        /// Register all necessary messages.
        /// </summary>
        protected virtual void RegisterMessages()
        {
            RegisterRequestShowMessageBoxMessage();
            RegisterRequestRestartCurrentApplicationMessage();
        }

        /// <summary>
        /// Perform clean up for view & view model
        /// </summary>
        protected virtual void Cleanup()
        {
            ViewHelper.Cleanup(this);
        }

        /// <summary>
        /// Register the RequestShowMessageBoxMessage from MyViewModelBase
        /// </summary>
        private void RegisterRequestShowMessageBoxMessage()
        {
            Messenger.Default.Register<string>(this, MyViewModelBase.RequestShowMessageBoxMessageToken, p =>
            {
                ViewHelper.RunAction(new Action(() =>
                {
                    MessageBox.Show(this, p, "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                }));
            });
        }

        /// <summary>
        /// Register the RequestRestartCurrentApplicationMessageToken from MyViewModelBase
        /// </summary>
        private void RegisterRequestRestartCurrentApplicationMessage()
        {
            Messenger.Default.Register<int>(this, MyViewModelBase.RequestRestartCurrentApplicationMessageToken, p =>
            {
                Process.Start(Application.ResourceAssembly.Location);
                Application.Current.Shutdown();
            });
        }
    }
}
